import { ref, inject } from "vue";
import moment from "moment";
import FileSaver from "file-saver";
// import XLSX from "xlsx";
import * as XLSX from "xlsx";
//导入uuid.js工具
import { useStore } from "vuex";

import "echarts-gl";
import { v4 as uuidv4 } from "uuid";
export function useConvert() {
  const getParametricEquation = (
    startRatio,
    endRatio,
    isSelected,
    isHovered,
    k,
    h
  ) => {
    // 计算
    let midRatio = (startRatio + endRatio) / 2;

    let startRadian = startRatio * Math.PI * 2;
    let endRadian = endRatio * Math.PI * 2;
    let midRadian = midRatio * Math.PI * 2;
    isSelected = false;
    k = typeof k !== "undefined" ? k : 1 / 3;
    let offsetX = isSelected ? Math.sin(midRadian) * 0.1 : 0;
    let offsetY = isSelected ? Math.cos(midRadian) * 0.1 : 0;
    let hoverRate = isHovered ? 1.05 : 1;
    return {
      u: {
        min: -Math.PI,
        max: Math.PI * 3,
        step: Math.PI / 32,
      },

      v: {
        min: 0,
        max: Math.PI * 2,
        step: Math.PI / 20,
      },

      x: function (u, v) {
        if (u < startRadian) {
          return (
            offsetX + Math.cos(startRadian) * (1 + Math.cos(v) * k) * hoverRate
          );
        }
        if (u > endRadian) {
          return (
            offsetX + Math.cos(endRadian) * (1 + Math.cos(v) * k) * hoverRate
          );
        }
        return offsetX + Math.cos(u) * (1 + Math.cos(v) * k) * hoverRate;
      },

      y: function (u, v) {
        if (u < startRadian) {
          return (
            offsetY + Math.sin(startRadian) * (1 + Math.cos(v) * k) * hoverRate
          );
        }
        if (u > endRadian) {
          return (
            offsetY + Math.sin(endRadian) * (1 + Math.cos(v) * k) * hoverRate
          );
        }
        return offsetY + Math.sin(u) * (1 + Math.cos(v) * k) * hoverRate;
      },

      z: function (u, v) {
        if (u < -Math.PI * 0.5) {
          return Math.sin(u);
        }
        if (u > Math.PI * 2.5) {
          return Math.sin(u) * h * 0.1;
        }
        return Math.sin(v) > 0 ? 1 * h * 0.1 : -1;
      },
    };
  };

  const getPie3D = (pieData, internalDiameterRatio, distance, alpha=50) => {
    let series = [];
    let sumValue = 0;
    let startValue = 0;
    let endValue = 0;
    let legendData = [];
    let k =
      typeof internalDiameterRatio !== "undefined"
        ? (1 - internalDiameterRatio) / (1 + internalDiameterRatio)
        : 1 / 3;
    for (let i = 0; i < pieData.length; i++) {
      sumValue += pieData[i].value;

      let seriesItem = {
        name:
          typeof pieData[i].name === "undefined"
            ? `series${i}`
            : pieData[i].name,
        type: "surface",
        parametric: true,
        wireframe: {
          show: false,
        },
        pieData: pieData[i],
        pieStatus: {
          selected: false,
          hovered: false,
          k: 1 / 10,
        },
      };
      if (typeof pieData[i].itemStyle != "undefined") {
        let itemStyle = {};
        typeof pieData[i].itemStyle.color != "undefined"
          ? (itemStyle.color = pieData[i].itemStyle.color)
          : null;
        typeof pieData[i].itemStyle.opacity != "undefined"
          ? (itemStyle.opacity = pieData[i].itemStyle.opacity)
          : null;

        seriesItem.itemStyle = itemStyle;
      }
      series.push(seriesItem);
    }
    for (let i = 0; i < series.length; i++) {
      endValue = startValue + series[i].pieData.value;

      series[i].pieData.startRatio = startValue / sumValue;
      series[i].pieData.endRatio = endValue / sumValue;
      series[i].parametricEquation = getParametricEquation(
        series[i].pieData.startRatio,
        series[i].pieData.endRatio,
        false,
        false,
        k,
        series[i].pieData.value
      );

      startValue = endValue;

      legendData.push(series[i].name);
    }

    let option = {
      legend: {
        show: false,
        textStyle: {
          color: "#FFFFFF",
          fontSize: 18,
        },
        data: legendData,
        formatter: (params) => {
          return params;
        },
      },
      title: {
        text: "设备总数/个",
        left: "center",
        top: "55%",
        textStyle: {
          color: "#fff",
          fontSize: 20,
          align: "center",
        },
      },
      graphic: {
        type: "text",
        left: "center",
        top: "40%",
        style: {
          text: pieData.reduce((sum, item) => sum + item.value, 0),
          textAlign: "center",
          fill: "#fff",
          fontSize: 29,
          fontWeight: 700,
        },
      },
      xAxis3D: {},
      yAxis3D: {},
      zAxis3D: {},
      grid3D: {
        viewControl: {
          autoRotate: false,
          distance: distance,
          alpha: alpha
        },
        left: "center",
        width: "80%",
        show: false,
        boxHeight: 20,
      },
      series: series,
    };
    return option;
  };

  /**
   * elemet-ui el-table数据导出为xlsx表格
   * @param {*} _targetId Element-UI el-table组件的id值
   */
  //  const exportTableAsXLSX = function(_targetId,name) {
  //       //根据table生成Book工作簿
  //       let wb = XLSX.utils.table_to_book(document.getElementById(_targetId));
  //        // 获取工作簿中的所有工作表
  //   let sheets = wb.Sheets;
  //   // 遍历所有工作表
  //   // for (let sheetName in sheets) {
  //   //   let sheet = sheets[sheetName];
  //   //   // 获取工作表中的所有单元格范围
  //   //   let range = XLSX.utils.decode_range(sheet["!ref"]);
  //   //   // 将所有单元格的格式设置为文本
  //   //   for (let i = range.s.r; i <= range.e.r; i++) {
  //   //     for (let j = range.s.c; j <= range.e.c; j++) {
  //   //       let cellAddress = XLSX.utils.encode_cell({ r: i, c: j });
  //   //       if (!sheet[cellAddress]) {
  //   //         continue;
  //   //       }
  //   //       sheet[cellAddress].z = "@";
  //   //     }
  //   //   }
  //   // }

  //   // 将 Book 工作簿作为输出
  //   let wbout = XLSX.write(wb, {
  //     bookType: "xlsx",
  //     bookSST: true,
  //     type: "array",
  //   });

  //       //尝试将当前table内容保存为excel文件
  //       try {
  //         let currentDate = new Date();
  //         let fileName = currentDate.getFullYear().toString() +
  //                        (currentDate.getMonth() + 1).toString().padStart(2, "0") +
  //                        currentDate.getDate().toString().padStart(2, "0") +
  //                        currentDate.getHours().toString().padStart(2, "0") +
  //                        currentDate.getMinutes().toString().padStart(2, "0");
  //         FileSaver.saveAs(
  //           // 被导出的 blob 二进制对象
  //           new Blob([wbout], { type: "application/octet-stream" }),
  //           // 导出文件的名称+后缀名
  //           name+"-"+fileName + ".xlsx"
  //         );
  //       } catch (e) {
  //           if (typeof console != "undefined") console.log(e, wbout);
  //       }
  //   };
  const store = useStore();
  const exportTableAsXLSX = function (_targetId, name) {
    // 根据 table 生成 Book 工作簿
    // let wb = XLSX.utils.table_to_book(document.getElementById(_targetId));
    let wb = XLSX.utils.table_to_book(document.getElementById(_targetId), {
      raw: true,
    });
    // 获取工作簿中的所有工作表
    let sheets = wb.Sheets;
    // 遍历所有工作表
    for (let sheetName in sheets) {
      let sheet = sheets[sheetName];
      // 获取工作表中的所有单元格范围
      let range = XLSX.utils.decode_range(sheet["!ref"]);
      // 将所有单元格的格式设置为文本
      for (let i = range.s.r; i <= range.e.r; i++) {
        for (let j = range.s.c; j <= range.e.c; j++) {
          let cellAddress = XLSX.utils.encode_cell({ r: i, c: j });
          if (!sheet[cellAddress]) {
            continue;
          }
          sheet[cellAddress].z = "@";
        }
      }
    }

    // 将 Book 工作簿作为输出
    let wbout = XLSX.write(wb, {
      bookType: "xlsx",
      bookSST: true,
      type: "binary",
    });

    // 尝试将当前 table 内容保存为 Excel 文件
    try {
      let currentDate = new Date();
      let fileName =
        currentDate.getFullYear().toString() +
        (currentDate.getMonth() + 1).toString().padStart(2, "0") +
        currentDate.getDate().toString().padStart(2, "0") +
        currentDate.getHours().toString().padStart(2, "0") +
        currentDate.getMinutes().toString().padStart(2, "0");
      FileSaver.saveAs(
        // 被导出的 blob 二进制对象
        new Blob([s2ab(wbout)], { type: "application/octet-stream" }),
        // 导出文件的名称+后缀名
        name + "_" + fileName + ".xlsx"
      );
    } catch (e) {
      if (typeof console != "undefined") console.log(e, wbout);
    }
  };

  // 将字符串转换为 ArrayBuffer 对象
  const s2ab = function (s) {
    let buf = new ArrayBuffer(s.length);
    let view = new Uint8Array(buf);
    for (let i = 0; i < s.length; ++i) {
      view[i] = s.charCodeAt(i) & 0xff;
    }
    return buf;
  };

  const timeToDate = (data) => {
    if (!data) {
      return;
    }

    return moment(data, "YYYY-MM-DD HH:mm:ss");
  };

  //日期时间统一
  const toDate = (date) => {
    return moment(date).format("YYYY-MM-DD");
  };

  const toTime = (date) => {
    //moment.now()
    return moment(moment.now()).format("HH:mm:ss");
  };

  const toDatetime = (date) => {
    if (date == null || date.length < 3) {
      return "";
    }
    return moment(date).format("YYYY-MM-DD HH:mm");
  };
  const toDatetimeAll = (date) => {
    if (date == null || date.length < 3) {
      return "";
    }
    return moment(date).format("YYYY-MM-DD HH:mm:ss");
  };
  const baseUrl = ref();
  const errImage = "";
  /**
   * 将jsonStr 转化为 能被直接被element ui image-view读取的urls
   * @param jsonStr
   */
  const toUrls = (jsonStr) => {
    //  console.log(jsonStr,'jsonStr');
    if (jsonStr == null || jsonStr.length < 5) {
      return [errImage];
    }
    let images = JSON.parse(jsonStr);
    let tempStringArray = [];
    for (let image of images) {
      tempStringArray.push(store.getters["getOssAliuncs"] + image);
    }

    if (tempStringArray != undefined && tempStringArray.length > 0) {
      console.log("tempStringArray", tempStringArray);

      return tempStringArray;
    } else {
      return [errImage];
    }
  };

  const toUrl = (jsonStr) => {
    let urls = toUrls(jsonStr);
    return urls[0];
  };

  const toSingeUrl = (jsonStr) => {
    return store.getters["getOssAliuncs"] + jsonStr;
  };

  /**
   *  将文件size转化为带单位的大小
   * @param {*} value 文件大小size
   */
  const renderSize = (value) => {
    if (null == value || value == "") {
      return "";
    }
    var unitArr = new Array(
      "Bytes",
      "KB",
      "MB",
      "GB",
      "TB",
      "PB",
      "EB",
      "ZB",
      "YB"
    );
    var index = 0;
    var srcsize = parseFloat(value);
    index = Math.floor(Math.log(srcsize) / Math.log(1024));
    var size = srcsize / Math.pow(1024, index);
    size = size.toFixed(2); //保留的小数位数
    return size + unitArr[index];
  };

  /**
   * dateRange 2 startTime
   */
  const dateRange2StartTime = (dateRange) => {
    if (null == dateRange || dateRange == "") {
      return "";
    }
    console.log(dateRange);
    console.log("moment", moment(dateRange[0]).format("YYYY-MM-DDTHH:mm:ss"));
    return moment(dateRange[0]).format("YYYY-MM-DDTHH:mm:ss");
  };
  /**
   * dateRange 2 endTime
   */
  const dateRange2EndTime = (dateRange) => {
    if (null == dateRange || dateRange == "") {
      return "";
    }
    return moment(dateRange[1]).format("YYYY-MM-DDTHH:mm:ss");
  };

  const startAndEndTime2dateRange = (start, end) => {
    return [start, end];
  };

  const fileName2suffix = (fileName) => {
    return fileName.substring(fileName.lastIndexOf(".") + 1);
  };
  
  const flattenArray=(arr)=> {
    let result = [];
    arr.forEach(item => {
        if (Array.isArray(item)) {
            result = result.concat(flattenArray(item)); // 递归调用，处理嵌套数组
        } else {
            result.push(item); // 如果不是数组，则直接添加到结果数组中
        }
    });
    return result;
}



  // 通过返回值暴露所管理的状态
  return {
    getParametricEquation,
    getPie3D,
    exportTableAsXLSX,
    timeToDate,
    toDate,
    toTime,
    toDatetime,
    toUrls,
    toUrl,
    renderSize,
    dateRange2StartTime,
    dateRange2EndTime,
    startAndEndTime2dateRange,
    toSingeUrl,
    fileName2suffix,
    toDatetimeAll,
    flattenArray
  };
}
